<template>
    <a-form ref="formRef" :model="formState" :label-col="labelCol" :wrapper-col="wrapperCol"
        class="adaptive-search-form">
        <a-row :gutter="[16, 16]" align="middle">
            <template v-for="(item, index) in visibleItems" :key="index">
                <a-col v-if="!item.hidden && (isExpanded || index < visibleCount)" :xxl="item.xxl || 6"
                    :xl="item.xl || 8" :lg="item.lg || 8" :md="item.md || 12" :sm="item.sm || 24" :xs="24">
                    <a-form-item :label="item.label" :name="item.name">
                        <!-- 输入框 -->
                        <a-input class="custom-input" v-if="item.type === 'input'" v-model:value="formState[item.name]"
                            :placeholder="item.placeholder || `请输入${item.label}`"
                            :allow-clear="item.allowClear ?? false" />

                        <!-- 下拉选择 -->
                        <MASelect v-else-if="item.type === 'select'" v-model:value="formState[item.name]"
                            :placeholder="item.placeholder || `请选择${item.label}`" :options="item.options"
                            :mode="item.mode" @change="(val, row) => item.onChange?.(val, row)"
                            :styles="{ width: '99%' }" />

                        <!-- 日期选择 -->
                        <a-date-picker v-else-if="item.type === 'date'" v-model:value="formState[item.name]"
                            :placeholder="item.placeholder || `请选择${item.label}`"
                            :value-format="item.valueFormat || 'YYYY-MM-DD'" :format="item.format || 'YYYY-MM-DD'"
                            style="width: 100%" />

                        <!-- 日期范围选择 -->
                        <a-range-picker v-else-if="item.type === 'range'" v-model:value="formState[item.name]"
                            :placeholder="item.placeholder || ['开始日期', '结束日期']"
                            :value-format="item.valueFormat || 'YYYY-MM-DD'" :format="item.format || 'YYYY-MM-DD'"
                            :show-time="item.showTime || false" style="width: 100%" />

                        <!-- 自定义插槽 -->
                        <slot v-else-if="item.type === 'slot'" :name="item.slotName || item.name" :item="item"
                            :formState="formState" />
                    </a-form-item>
                </a-col>
            </template>

            <!-- 展开收起按钮 -->
            <a-col :xxl="6" :xl="8" :lg="8" :md="12" :sm="24" :xs="24" class="form-actions">
                <a-button @click="toggleExpand" class="toggle-btn">
                    <template #icon>
                        <CaretUpOutlined v-if="isExpanded" />
                        <CaretDownOutlined v-else />
                    </template>
                    {{ isExpanded ? '收起' : '展开' }}
                </a-button>
            </a-col>
        </a-row>

        <!-- 操作按钮 - 跟随在表单项后 -->
        <a-row :gutter="[16, 16]">
            <template v-if="showActionsInline">
                <a-col :span="14" class="action-buttons" push="2">
                    <a-button type="primary" @click="handleSearch">
                        <template #icon>
                            <SearchOutlined />
                        </template>
                        搜索
                    </a-button>
                    <a-button style="margin-left: 8px" @click="handleReset">
                        <template #icon>
                            <RedoOutlined />
                        </template>
                        重置
                    </a-button>
                </a-col>
            </template>
        </a-row>
    </a-form>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue';
import { SearchOutlined, RedoOutlined, CaretUpOutlined, CaretDownOutlined } from '@ant-design/icons-vue';

const props = defineProps({
    // 表单配置项
    items: {
        type: Array,
        required: true,
        default: () => [],
    },
    // 标签布局
    labelCol: {
        type: Object,
        default: () => ({ style: { width: "110px" } }),
    },
    // 控件布局
    wrapperCol: {
        type: Object,
        default: () => ({ span: 16 }),
    },
    // 初始表单值
    initialValues: {
        type: Object,
        default: () => ({}),
    },
    auth: {
        type: String
    }
});

const emit = defineEmits(['search', 'reset', 'update:modelValue']);

const formRef = ref();
const formState = reactive({ ...props.initialValues });
const windowWidth = ref(window.innerWidth);
const showActionsInline = ref(true);
const isExpanded = ref(false);

// 计算当前可见的表单项
const visibleItems = computed(() => {
    return props.items.filter(item => !item.hidden);
});

// 计算一行显示的表单项数量
const visibleCount = computed(() => {
    if (windowWidth.value < 768) { // 移动端
        return 1;
    } else if (windowWidth.value < 992) { // 平板
        return 2;
    } else if (windowWidth.value < 1600) { // 小桌面
        return 3;
    } else { // 大桌面
        return 4;
    }
});

// 切换展开收起状态
const toggleExpand = () => {
    isExpanded.value = !isExpanded.value;
};

// 计算是否应该内联显示操作按钮
const calculateActionsPosition = () => {
    const visibleCountValue = visibleCount.value;
    showActionsInline.value = (visibleItems.value.length <= visibleCountValue) || isExpanded.value;
};

// 处理窗口大小变化
const handleResize = () => {
    windowWidth.value = window.innerWidth;
    calculateActionsPosition();
};

onMounted(() => {
    window.addEventListener('resize', handleResize);
    calculateActionsPosition();
});

onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
});

// 处理表单项，添加默认值
const formItems = computed(() => {
    return props.items.map(item => {
        // 初始化表单值
        if (item.value !== undefined && formState[item.name] === undefined) {
            formState[item.name] = item.value;
        }
        return item;
    });
});

// 搜索方法
const handleSearch = () => {
    emit('search', formState);
};

// 重置方法
const handleReset = () => {
    formRef.value.resetFields();
    emit('reset');
};

// 清空指定字段
const clearField = (name, value) => {
    formState[name] = value;
}

// 暴露方法给父组件
defineExpose({
    formRef,
    formState,
    reset: () => handleReset(),
    search: () => handleSearch(),
    clearField
});
</script>

<style scoped>
/* 使用深度选择器 */
:deep(.custom-input input::placeholder) {
    color: #7f7f7f;
}

.adaptive-search-form {
    width: 100%;
    padding: 16px;
    background: #fff;
    border-radius: 2px;
    /* margin-bottom: 8; */
}

.action-buttons {
    display: flex;
    align-items: center;
    padding-top: 4px;
}

.action-buttons-row {
    margin-top: 8px;
    justify-content: flex-end;
}

.form-actions {
    display: flex;
    align-items: center;
    justify-content: center;
    padding-top: 4px;

    .toggle-btn {
        margin-right: 12px;
    }

    .search-btn {
        margin-right: 12px;
    }

    .reset-btn {
        margin-right: 0;
    }
}

:deep(.ant-form-item) {
    margin-bottom: 0;
}
</style>
